<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h1>仪表板</h1>
      <p>欢迎回来，{{ authStore.user?.name || authStore.user?.username }}！</p>
    </div>

    <!-- 学生仪表板 -->
    <template v-if="authStore.isStudent">
      <el-row :gutter="20" class="stats-row">
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon courses">
                <el-icon><Reading /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ studentStats.selectedCourses }}</h3>
                <p>已选课程</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon credits">
                <el-icon><Trophy /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ studentStats.totalCredits }}</h3>
                <p>总学分</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon available">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ studentStats.availableCourses }}</h3>
                <p>可选课程</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="content-row">
        <el-col :span="24">
          <el-card>
            <template #header>
              <span>我的课程</span>
              <el-button style="float: right; padding: 3px 0" type="text" @click="$router.push('/my-courses')">
                查看全部
              </el-button>
            </template>
            <el-table :data="recentCourses" v-loading="loading">
              <el-table-column prop="course_name" label="课程名称" />
              <el-table-column prop="course_code" label="课程代码" />
              <el-table-column prop="credit" label="学分" />
              <el-table-column prop="teacher_name" label="教师" />
              <el-table-column prop="selection_date" label="选课时间">
                <template #default="scope">
                  {{ formatDate(scope.row.selection_date) }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </template>

    <!-- 教师仪表板 -->
    <template v-if="authStore.isTeacher">
      <el-row :gutter="20" class="stats-row">
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon courses">
                <el-icon><Reading /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ teacherStats.taughtCourses }}</h3>
                <p>授课数量</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon students">
                <el-icon><UserFilled /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ teacherStats.totalStudents }}</h3>
                <p>学生总数</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon credits">
                <el-icon><Trophy /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ teacherStats.totalCredits }}</h3>
                <p>授课学分</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="content-row">
        <el-col :span="24">
          <el-card>
            <template #header>
              <span>我的授课</span>
              <el-button style="float: right; padding: 3px 0" type="text" @click="$router.push('/teacher/courses')">
                查看全部
              </el-button>
            </template>
            <el-table :data="teacherCourses" v-loading="loading">
              <el-table-column prop="name" label="课程名称" />
              <el-table-column prop="code" label="课程代码" />
              <el-table-column prop="credit" label="学分" />
              <el-table-column prop="current_enrollment" label="已选人数" />
              <el-table-column prop="capacity" label="容量" />
              <el-table-column label="选课率">
                <template #default="scope">
                  {{ ((scope.row.current_enrollment / scope.row.capacity) * 100).toFixed(1) }}%
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </template>

    <!-- 管理员仪表板 -->
    <template v-if="authStore.isAdmin">
      <el-row :gutter="20" class="stats-row">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon users">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ adminStats.totalUsers }}</h3>
                <p>总用户数</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon courses">
                <el-icon><Reading /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ adminStats.totalCourses }}</h3>
                <p>总课程数</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon selections">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ adminStats.totalSelections }}</h3>
                <p>总选课数</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon active">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stat-info">
                <h3>{{ adminStats.activeSelections }}</h3>
                <p>有效选课</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="content-row">
        <el-col :span="12">
          <el-card>
            <template #header>
              <span>用户角色分布</span>
            </template>
            <div class="role-stats">
              <div class="role-item">
                <span class="role-label">学生：</span>
                <span class="role-count">{{ adminStats.studentCount }}</span>
              </div>
              <div class="role-item">
                <span class="role-label">教师：</span>
                <span class="role-count">{{ adminStats.teacherCount }}</span>
              </div>
              <div class="role-item">
                <span class="role-label">管理员：</span>
                <span class="role-count">{{ adminStats.adminCount }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <template #header>
              <span>快速操作</span>
            </template>
            <div class="quick-actions">
              <el-button type="primary" @click="$router.push('/admin/users')">
                <el-icon><User /></el-icon>
                用户管理
              </el-button>
              <el-button type="success" @click="$router.push('/admin/courses')">
                <el-icon><Reading /></el-icon>
                课程管理
              </el-button>
              <el-button type="info" @click="$router.push('/admin/selections')">
                <el-icon><Document /></el-icon>
                选课记录
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </template>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { getMyEnrollments } from '@/api/selection'
import { getAllCourses } from '@/api/course'
import { getAllUsers } from '@/api/user'
import { getAllSelections } from '@/api/selection'
import {
  Reading,
  Trophy,
  Document,
  UserFilled,
  User,
  CircleCheck
} from '@element-plus/icons-vue'

const authStore = useAuthStore()
const loading = ref(false)

// 学生统计数据
const studentStats = reactive({
  selectedCourses: 0,
  totalCredits: 0,
  availableCourses: 0
})

// 教师统计数据
const teacherStats = reactive({
  taughtCourses: 0,
  totalStudents: 0,
  totalCredits: 0
})

// 管理员统计数据
const adminStats = reactive({
  totalUsers: 0,
  totalCourses: 0,
  totalSelections: 0,
  activeSelections: 0,
  studentCount: 0,
  teacherCount: 0,
  adminCount: 0
})

const recentCourses = ref([])
const teacherCourses = ref([])

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 获取学生数据
const fetchStudentData = async () => {
  try {
    loading.value = true
    // 获取我的选课
    const selectionRes = await getMyEnrollments({ status: 'selected', limit: 5 })
    if (selectionRes.code === 0) {
      recentCourses.value = selectionRes.data.selections
      studentStats.selectedCourses = selectionRes.data.total
      studentStats.totalCredits = selectionRes.data.selections.reduce((sum, item) => sum + (item.credit || 0), 0)
    }

    // 获取可选课程总数
    const coursesRes = await getAllCourses({ limit: 1 })
    if (coursesRes.code === 0) {
      studentStats.availableCourses = coursesRes.data.total
    }
  } catch (error) {
    console.error('获取学生数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取教师数据
const fetchTeacherData = async () => {
  try {
    loading.value = true
    // 获取我的授课
    const coursesRes = await getAllCourses({ teacherId: authStore.user.id, limit: 5 })
    if (coursesRes.code === 0) {
      teacherCourses.value = coursesRes.data.courses
      teacherStats.taughtCourses = coursesRes.data.total
      teacherStats.totalStudents = coursesRes.data.courses.reduce((sum, item) => sum + (item.current_enrollment || 0), 0)
      teacherStats.totalCredits = coursesRes.data.courses.reduce((sum, item) => sum + (item.credit || 0), 0)
    }
  } catch (error) {
    console.error('获取教师数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取管理员数据
const fetchAdminData = async () => {
  try {
    loading.value = true
    
    // 获取用户统计
    const usersRes = await getAllUsers({ limit: 1 })
    if (usersRes.code === 0) {
      adminStats.totalUsers = usersRes.data.total
    }

    // 获取各角色用户数量
    const studentRes = await getAllUsers({ role: 'student', limit: 1 })
    const teacherRes = await getAllUsers({ role: 'teacher', limit: 1 })
    const adminRes = await getAllUsers({ role: 'admin', limit: 1 })
    
    if (studentRes.code === 0) adminStats.studentCount = studentRes.data.total
    if (teacherRes.code === 0) adminStats.teacherCount = teacherRes.data.total
    if (adminRes.code === 0) adminStats.adminCount = adminRes.data.total

    // 获取课程统计
    const coursesRes = await getAllCourses({ limit: 1 })
    if (coursesRes.code === 0) {
      adminStats.totalCourses = coursesRes.data.total
    }

    // 获取选课统计
    const selectionsRes = await getAllSelections({ limit: 1 })
    if (selectionsRes.code === 0) {
      adminStats.totalSelections = selectionsRes.data.total
    }

    const activeSelectionsRes = await getAllSelections({ status: 'selected', limit: 1 })
    if (activeSelectionsRes.code === 0) {
      adminStats.activeSelections = activeSelectionsRes.data.total
    }
  } catch (error) {
    console.error('获取管理员数据失败:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  if (authStore.isStudent) {
    fetchStudentData()
  } else if (authStore.isTeacher) {
    fetchTeacherData()
  } else if (authStore.isAdmin) {
    fetchAdminData()
  }
})
</script>

<style scoped>
.dashboard {
  max-width: 1200px;
  margin: 0 auto;
}

.dashboard-header {
  margin-bottom: 24px;
}

.dashboard-header h1 {
  font-size: 28px;
  color: #303133;
  margin: 0 0 8px 0;
}

.dashboard-header p {
  color: #909399;
  margin: 0;
  font-size: 16px;
}

.stats-row {
  margin-bottom: 24px;
}

.content-row {
  margin-bottom: 24px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-icon.courses {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.credits {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.available {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.students {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-icon.users {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.stat-icon.selections {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.stat-icon.active {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
}

.stat-info h3 {
  font-size: 32px;
  color: #303133;
  margin: 0 0 4px 0;
  font-weight: 600;
}

.stat-info p {
  color: #909399;
  margin: 0;
  font-size: 14px;
}

.role-stats {
  padding: 16px 0;
}

.role-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.role-item:last-child {
  border-bottom: none;
}

.role-label {
  font-size: 14px;
  color: #606266;
}

.role-count {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 16px 0;
}

.quick-actions .el-button {
  justify-content: flex-start;
  padding: 12px 20px;
}
</style> 